package com.leetcode.problems008;


/**
 * @Description https://leetcode-cn.com/problems/string-to-integer-atoi/
 * @Date 2021/11/20 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution2 {

    /**
     * 字符串转化为数字
     * @param s 输入的字符串
     * @return
     */
    public int myAtoi(String s) {
        if(s == null || s.length() == 0){
            return 0;
        }
        int size = s.length();
        //去除空格
        int i = 0;
        for (;i < size && s.charAt(i) == ' '; i++ ) {
        }
        if(i >= size){
            return 0;
        }
        int n = 0;
        boolean isPlus = true;
        if(s.charAt(i) == '-'){
            isPlus = false;
            i++;
        }else if(s.charAt(i) == '+'){
            i++;
        }
        for (; i < size; i++) {
            if(isNotNumberChar(s, i)){
                break;
            }
            int curNum = s.charAt(i) - '0';
            if(n > Integer.MAX_VALUE / 10 || (n == Integer.MAX_VALUE / 10 && curNum > 7)){
                return isPlus ? Integer.MAX_VALUE:Integer.MIN_VALUE;
            }
            n = n * 10 + curNum;
        }
        return isPlus ? n : -1 * n;
    }

    private boolean isNotNumberChar(String s, int i) {
        return s.charAt(i) < '0' || s.charAt(i) > '9';
    }

    public static void main(String[] args) {
        System.out.println(new Solution2().myAtoi("2147483648"));
    }
}
